<template>
  <el-dialog
    title="编辑部门"
    :visible.sync="isShow"
    width="40%"
    @close="closeEvent"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          placeholder="请选择负责人"
          @focus="selectEvent"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="footer">
      <el-button @click="isShow = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments.js'
export default {
  name: '',
  props: {
    initList: { type: Array, default: () => [] }
  },
  data() {
    return {
      mode: 'add',
      item: '',
      userList: [],
      isShow: false,
      form: {
        //	string	非必须		部门名称
        name: '',
        //	string	非必须		部门编码，同级部门不可重复
        code: '',
        //	string	非必须		负责人名称
        manager: '',
        //	string	非必须		介绍
        introduce: '',
        //	string	非必须		父级部门ID
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          // 需求:同级部门名不能重复
          {
            validator: (rule, value, callback) => {
              let temp = ''
              // 新增时点击项子级目录名不能重复
              if (this.mode === 'add') {
                temp = this.initList.filter((item) => {
                  return item.pid === this.item.id
                })
                // 编辑时点击项同级目录名除了自己不能重复
              } else {
                temp = this.initList.filter((item) => {
                  return item.pid === this.item.pid && item.id !== this.item.id
                })
              }
              // console.log(temp)
              const res = temp.some((item) => {
                return value === item.name
              })
              res
                ? callback(new Error('请不要输入重复的部门名:' + value))
                : callback()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          // code唯一性
          {
            validator: (rule, value, callback) => {
              let res = ''
              // 新增时code不能重复
              if (this.mode === 'add') {
                res = this.initList.some((item) => value === item.code)
                // 编辑时code除了自己不能重复
              } else {
                res = this.initList.some(
                  (item) => value === item.code && item.code !== this.item.code
                )
              }
              res
                ? callback(new Error('请不要输入重复的部门名:' + value))
                : callback()
            },
            trigger: 'change'
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  mounted() {
    // bus监听
    this.$bus.$on('show', (bol, item, mode = 'add') => {
      this.isShow = bol
      this.item = item
      this.mode = mode
      console.log('点击想:', item)
      if (this.mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  beforeDestroy() {
    // 销毁监听
    this.$bus.$off('show')
  },
  methods: {
    // 获取员工简单列表
    async selectEvent() {
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        // console.log(res)
        this.userList = res.data
      }
    },
    // 提交
    submit() {
      this.$refs.form.validate(async(res) => {
        if (res) {
          if (this.mode === 'add') {
            this.form.pid = this.item.id
            await companyDepartmentPost(this.form)
            this.$message.success('新增成功')
          } else {
            await companyDepartmentPut(this.form)
            this.$message.success('修改成功')
          }
          this.isShow = false
          this.$emit('getData')
        }
      })
    },
    closeEvent() {
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
    }
  }
}
</script>
<style scoped lang="scss">
.footer {
  text-align: center;
}
</style>
